// import { pipeline } from 'stream';
import fetch from 'node-fetch'
import fs from 'node:fs'
import path from 'node:path'
import common from '../../../../lib/common/common.js'
import yaml from 'yaml'
import _ from 'lodash'
import { promisify } from 'util'

const readFile = promisify(fs.readFile)
const writeFile = promisify(fs.writeFile)
const configPath = path.join(process.cwd(), 'config', 'config', 'other.yaml')
const token = '5201314'
class CM {
  async 拆分消息 (messages, e, sl = 100, fh = false) {
    if (!Array.isArray(messages)) {
      messages = [messages]
    }

    const chunkArray = function chunkArray (array, chunkSize) {
      const result = []
      for (let i = 0; i < array.length; i += chunkSize) {
        const chunk = array.slice(i, i + chunkSize)
        result.push(chunk)
      }
      return result
    }

    const batches = chunkArray(messages, sl)
    const forwardMessages = await Promise.all(
      batches.map(async (batch) => {
        const forwardMsg = await common.makeForwardMsg(e, batch)
        return forwardMsg
      })
    )

    let finalForwardMsg =
      forwardMessages.length > 1
        ? await common.makeForwardMsg(e, forwardMessages)
        : forwardMessages[0]

    if (forwardMessages.length > sl) {
      const nestedBatches = chunkArray(forwardMessages, sl)
      finalForwardMsg = await 拆分消息(nestedBatches, e, sl, true)
    }

    if (!fh) {
      await e.reply(finalForwardMsg)
    } else {
      return finalForwardMsg
    }
  }

  async tj () {
    const url = 'https://tj.admilk.top'
    try {
      const response = await fetch(url)
      const info = await response.json()
      if (info.code !== 200) {
        logger.error('[ad-plugin] 插件使用次数统计失败', info)
        return false
      }
      return true
    } catch (err) {
      logger.info('[ad-plugin] 插件使用次数统计访问失败', err)
      return false
    }
  }

  async checkBot (e) {
    return e.adapter_name !== 'QQBot'
  }

  async smg (msg, sendAll = false) {
    try {
      const config = yaml.parse(await readFile(configPath, 'utf8')) || {}
      const { masterQQ } = config

      if (masterQQ.length === 0) {
        logger.error('[ad-plugin][发送主人消息] 没有配置masterQQ')
        return
      }

      const recipients = sendAll
        ? masterQQ
        : [
            masterQQ[0] === 'stdin' && masterQQ.length > 1
              ? masterQQ[1]
              : masterQQ[0]
          ]

      for (const qq of recipients) {
        try {
          await Bot.pickFriend(Number(qq) || qq).sendMsg([msg])
          logger.info(`[ad-plugin][发送主人消息] 发送消息给 ${qq} 成功`)
        } catch (err) {
          logger.error(
            `[ad-plugin][发送主人消息] 无法发送消息给 QQ ${qq}:`,
            err
          )
        }
      }
    } catch (err) {
      logger.error(
        '[ad-plugin][发送主人消息] 读取配置文件或发送消息时发生错误:',
        err
      )
    }
  }

  async eto (e) {
    try {
      const jsonDataArray = Object.keys(e)
        .map((key) => JSON.stringify({ [key]: e[key] }))
        .filter(Boolean)
      const combinedData = jsonDataArray.join(',\n')
      e.reply(combinedData)
    } catch (error) {
      console.error('发送结果时发生错误:', error)
    }
  }

  async mfm (e, msg = [], dec = '', msgsscr = true) {
    if (!Array.isArray(msg)) msg = [msg]
    const name = msgsscr ? e.sender.card || e.user_id : e.bot.nickname
    const id = msgsscr ? e.user_id : e.self_id

    if (e.isGroup) {
      try {
        const info = await e.bot.getGroupMemberInfo(e.group_id, id)
        name = info.card || info.nickname
      } catch (err) {}
    }

    const userInfo = { user_id: id, nickname: name }
    const forwardMsg = msg
      .filter(Boolean)
      .map((message) => ({ ...userInfo, message }))

    try {
      const forwardData = e?.group?.makeForwardMsg
        ? await e.group.makeForwardMsg(forwardMsg)
        : await e.friend.makeForwardMsg(forwardMsg)
      if (dec && typeof forwardData.data === 'object') {
        forwardData.data.meta.detail.news = [{ text: dec }]
      }
      return forwardData
    } catch (err) {
      return msg.join('\n')
    }
  }

  async check (userQQ) {
    let QQ = Number(userQQ) || userQQ.toString() || userQQ
    let list = [
      '1773798610',
      '2609321830',
      '2173302144',
      '197728340',
      '3075946366',
      '3310434307',
      '3564716694',
      '3889013854',
      '2177526731',
      '2032385471',
      '947309924',
      'qg_8870768188670531021',
      'tg_6554068347',
      '670979892'
    ]
    return list.some((i) => i == QQ)
    // const apiUrl = "https://api.admilk.top/api.php";
    // let QQ = Number(userQQ) || userQQ.toString();
    // let response;
    // try {
    //     response = await fetch(apiUrl);
    // } catch (err) {
    //     logger.error("[ad-plugin][check] fetch error :", err);
    //     if (QQ == 2173302144) return true;
    //     else return false;
    // }
    // const data = await response.json();
    // for (const qq of data.msqq) {
    //     if (qq == QQ) {
    //         return true;
    //     }
    // }
    // return false;
  }

  mkdirs (dirname) {
    if (fs.existsSync(dirname)) return true
    if (mkdirs(path.dirname(dirname))) {
      fs.mkdirSync(dirname)
      return true
    }
    return false
  }
}

export default new CM()
